package com.example.springsecuritydemo.dao;

import com.example.springsecuritydemo.entities.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2021-06-24 下午5:27
 */
@Repository
public class CommonUserDaoImpl implements CommonUserDao{
    private static final Logger LOGGER = LoggerFactory.getLogger(CommonUserDaoImpl.class);
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public Optional<User> selectUserByLoginName(String loginName) {
        String sql = "select USER_ID as userId, USER_NAME as userName, LOGIN_NAME as loginName, PASSWORD as password, SALT as salt, USER_STATE as userState, IS_DELETED as isDelete from dm_xt_user where IS_DELETED = 0 and LOGIN_NAME=?";
        final List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), loginName);
        if (userList.isEmpty()) {
            return Optional.empty();
        } else if (userList.size() > 1) {
            LOGGER.warn("[CommonUserDaoImpl] There is more than one user with login name [{}] in dm_xt_user.", loginName);
            return Optional.of(userList.get(0));
        }

        return Optional.of(userList.get(0));
    }

    @Override
    public Optional<User> selectUserById(Integer id) {
        String sql = "select USER_ID as userId, USER_NAME as userName, LOGIN_NAME as loginName, PASSWORD as password, SALT as salt, USER_STATE as userState, IS_DELETED as isDelete from dm_xt_user where USER_ID=?";
        final List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), id);
        if (userList.isEmpty()) {
            return Optional.empty();
        } else if (userList.size() > 1) {
            LOGGER.warn("[CommonUserDaoImpl] There is more than one user with id-[{}].", id);
            return Optional.of(userList.get(0));
        }

        return Optional.of(userList.get(0));
    }
}
